package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Sound;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Collections;
import java.util.List;

/**
 * @Author: cloudy
 * @Description:
 * @Date: Created in 10:17 2021/1/17
 * @ModifiedBy:
 */
@Service(version = "1.0.0")
public class PeachBlossomApiImpl implements PeachBlossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean sendMsg(Sound sound) {
        try {
            sound.setId(ObjectId.get());
            sound.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(sound);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Sound getMsg(Long userId) {
        try {
            Query query = Query.query(Criteria.where("userId").ne(userId));
            List<Sound> sounds = this.mongoTemplate.find(query, Sound.class);
            if (sounds != null) {
                Collections.shuffle(sounds);
                Sound sound = sounds.get(0);
                this.mongoTemplate.remove(sound);
                return sound;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
